package com.recipedb.sprint.controller;

import com.recipedb.sprint.entity.Sessions;
import com.recipedb.sprint.entity.Users;
import com.recipedb.sprint.service.AdminService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.recipedb.sprint.security.JwtUtil;


@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private final AdminService adminService;


    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }

    // 管理员登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        try {
            String account = request.get("account");
            String password = request.get("password");
            Map<String, Object> data = adminService.adminLogin(account, password);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "管理员登录成功");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    // 查询所有用户（需管理员Token）
    @GetMapping("/users")
    public ResponseEntity<Map<String, Object>> getAllUsers(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) String keyword) {
        try {
            // 1. 截取 Bearer 前缀，获取纯 Token
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            if (JwtUtil.validateToken(pureToken) == null) {
                throw new RuntimeException("Token无效");
            }
            List<Users> users = adminService.getAllUsers(keyword);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", users);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    // 数据统计看板
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics(
            @RequestHeader("Authorization") String token) {
        try {
            // 1. 截取 Bearer 前缀，获取纯 Token
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 2. 用 JwtUtil 校验 Token 有效性
            if (JwtUtil.validateToken(pureToken) == null) {
                throw new RuntimeException("Token无效或已过期");
            }
            Map<String, Object> stats = adminService.getStatistics();

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", stats);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    // 新增用户还没写，删除用户还得改

    // 查询单个用户（按用户ID）
    @GetMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> getUserById(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId) {
        try {
            // 管理员Token校验
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            Users user = adminService.getUserById(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "查询成功");
            response.put("data", user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PutMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> updateUser(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @RequestBody Users user) {
        try {
            // 管理员Token校验
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            // 禁止修改管理员（userid=0）
            if (userId == 0L) {
                throw new RuntimeException("禁止修改管理员账号");
            }

            adminService.updateUser(userId, user);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "用户编辑成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId) {
        try {
            // 管理员Token校验
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            // 禁止删除管理员（userid=0）
            if (userId == 0L) {
                throw new RuntimeException("禁止删除管理员账号");
            }

            adminService.deleteUser(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "用户删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }


    /**
     * 管理员查询指定用户的所有会话（简洁版）
     * 路径：/api/admin/sessions/user/{userId}
     */
    @GetMapping("/sessions/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserSessions(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId) {
        try {
            // 管理员Token校验
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            // 2. 调用服务层查询
            List<Sessions> sessions = adminService.getUserSessions(userId);

            // 3. 组装返回结果（与现有接口格式一致：code+msg+data）
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "查询用户会话成功");
            response.put("data", sessions); // 包含会话所有字段（prompt、answer、llmProvider等）
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }



    /**
     * 管理员查询所有会话（全局查看）
     * 路径：/api/admin/sessions/all
     */
    @GetMapping("/sessions/all")
    public ResponseEntity<Map<String, Object>> getAllSessions(
            @RequestHeader("Authorization") String token) {
        try {
            // 1. 管理员权限校验（同上）
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            // 2. 调用服务层查询所有会话
            List<Sessions> sessions = adminService.getAllSessions();

            // 3. 组装返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "查询所有会话成功");
            response.put("data", sessions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 管理员删除单个 Session
     * 路径：/api/admin/sessions/{sessionId}
     */
    @DeleteMapping("/sessions/{sessionId}")
    public ResponseEntity<Map<String, Object>> deleteSession(
            @RequestHeader("Authorization") String token,
            @PathVariable Long sessionId) {
        try {
            // 管理员权限校验（复用现有逻辑）
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            String username = JwtUtil.validateToken(pureToken);
            if (username == null || !"root".equals(username)) {
                throw new RuntimeException("无管理员权限");
            }

            // 调用服务层删除
            adminService.deleteSession(sessionId);

            // 组装返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "Session删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }


}